﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data;
using System.IO;
using BL;
using Entities;
using System.Media;
using Microsoft.VisualBasic;


namespace StockVentas
{
    public partial class frmStockComp : Form
    {
        private frmStockComp instancia;
        public DataSet dsStockMov;
        public DataSet dsStock;
        DataTable tblStockMov;
        DataTable tblStockMovDetalle;
        DataTable tblOriginalDetalle;
        DataView viewStockMov;
        DataView viewStockMovDetalle;
        DataRowView rowView;
        DataTable tblLocales;
        DataTable tblArticulos;
        DataView viewOrigen;
        DataView viewDestino;
        string strFilePath;
        public string PK = string.Empty;
        frmProgress progreso;
        private int intFila;

        public frmStockComp()
        {
            InitializeComponent();
            instancia = this;
            strFilePath = Application.StartupPath + "\\Datasets_xml\\";
            tblLocales = new DataTable();
            tblLocales.ReadXml(strFilePath + "Locales.xml");
            viewOrigen = new DataView(tblLocales);
            viewOrigen.RowFilter = "IdLocalLOC <>'2'";
            cmbOrigen.ValueMember = "IdLocalLOC";
            cmbOrigen.DisplayMember = "NombreLOC";
            cmbOrigen.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbOrigen.DataSource = viewOrigen;
            viewDestino = new DataView(tblLocales);
            viewDestino.RowFilter = "IdLocalLOC = '13'";
            cmbDestino.ValueMember = "IdLocalLOC";
            cmbDestino.DisplayMember = "NombreLOC";
            cmbDestino.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbDestino.DataSource = viewDestino;
            cmbOrigen.SelectedIndex = -1;
            cmbDestino.SelectedIndex = -1;
            this.AutoValidate = System.Windows.Forms.AutoValidate.EnablePreventFocusChange;
            
        }

        private void frmStockMov_Load(object sender, EventArgs e)
        {
            dsStockMov = BL.StockMovBLL.CrearDataset();
            tblStockMov = dsStockMov.Tables["StockMov"];
            tblStockMov.PrimaryKey = new DataColumn[] { tblStockMov.Columns["IdMovMSTK"] };
            dsStockMov.Tables["StockMovDetalle"].Columns.Remove("DescripcionART");
            tblStockMovDetalle = dsStockMov.Tables["StockMovDetalle"];
            tblStockMovDetalle.PrimaryKey = new DataColumn[] { tblStockMovDetalle.Columns["IdMSTKD"] };
            viewStockMov = new DataView(tblStockMov);
            viewStockMovDetalle = new DataView(tblStockMovDetalle);
            lblNro.ForeColor = System.Drawing.Color.DarkRed;
            if (PK == "") //registro nuevo
            {
                Random rand = new Random();
                int clave = rand.Next(1, 2000000000);
                lblNro.Text = clave.ToString();
                viewStockMov.RowStateFilter = DataViewRowState.Added;
                viewStockMovDetalle.RowStateFilter = DataViewRowState.Added;
                rowView = viewStockMov.AddNew();
                rowView["IdMovMSTK"] = clave.ToString();
                rowView["OrigenMSTK"] = 1;
                rowView["DestinoMSTK"] = 13;
                rowView["FechaMSTK"] = DateTime.Today;
                rowView["CompensaMSTK"] = 1;
                rowView.EndEdit();
            }
            else // editar registros
            {
                viewStockMov.RowFilter = "IdMovMSTK = '" + PK + "'";
                rowView = viewStockMov[0];
                viewStockMovDetalle.RowFilter = "IdMovMSTKD = '" + PK + "'";
                tblOriginalDetalle = viewStockMovDetalle.ToTable();
                lblNro.Text = viewStockMov[0][0].ToString();
            }
            dateTimePicker1.DataBindings.Add("Text", rowView, "FechaMSTK", false, DataSourceUpdateMode.OnPropertyChanged);
            cmbOrigen.DataBindings.Add("SelectedValue", rowView, "OrigenMSTK", false, DataSourceUpdateMode.OnPropertyChanged);
            cmbDestino.DataBindings.Add("SelectedValue", rowView, "DestinoMSTK", false, DataSourceUpdateMode.OnPropertyChanged);
            rowView.CancelEdit();
            dgvDatos.DataSource = viewStockMovDetalle;
            dgvDatos.EditMode = DataGridViewEditMode.EditOnKeystroke;
            dgvDatos.Columns["IdArticuloMSTKD"].HeaderText = "Código";
            dgvDatos.Columns["IdMovMSTKD"].Visible = false;
            dgvDatos.Columns["IdMSTKD"].Visible = false;
            dgvDatos.Columns["CompensaMSTKD"].Visible = false;
            dgvDatos.Columns["OrigenMSTKD"].Visible = false;
            dgvDatos.Columns["DestinoMSTKD"].Visible = false;
            dgvDatos.Columns["CantidadMSTKD"].Width = 100;
            dgvDatos.Columns["CantidadMSTKD"].HeaderText = "Cantidad";
            tblArticulos = new DataTable();
            tblArticulos.ReadXml(strFilePath + "Articulos.xml");
            tblArticulos.TableName = "Articulos";
            DataGridViewTextBoxColumn columnaDescripcion = new DataGridViewTextBoxColumn();
            columnaDescripcion.Name = "Descripcion";
            columnaDescripcion.HeaderText = "Descripción";
            dgvDatos.Columns.Insert(3, columnaDescripcion);
            dgvDatos.Columns[3].Width = 500;
            dgvDatos.Columns[3].ReadOnly = true;
            cmbOrigen.Visible = false;
            btnArticulos.Enabled = false;
            this.dgvDatos.RowValidating += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.ValidarFila);
        }

        private void frmStockMov_Activated(object sender, EventArgs e)
        {
            if (PK != "")
            {
                foreach (DataGridViewRow fila in dgvDatos.Rows)
                {
                    if (!fila.IsNewRow)
                    {
                        string articulo = fila.Cells[2].Value.ToString();
                        DataRow[] foundRow = tblArticulos.Select("IdArticuloART = '" + articulo + "'");
                        fila.Cells[3].Value = foundRow[0]["DescripcionART"].ToString();
                    }
                }
            }
        }

        private void dgvDatos_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["CompensaMSTKD"].Value = 1;
        }

        private void dgvDatos_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvDatos.CurrentCell.ColumnIndex == 3)
            {
                SendKeys.Send("{TAB}");
            }
        }

        private void dgvDatos_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (String.IsNullOrEmpty(dgvDatos[0, e.RowIndex].Value.ToString()))
            {
                Random rand = new Random();
                int clave = rand.Next(1, 2000000000);
                bool existe = true;
                while (existe == true)
                {
                    DataRow foundRow = dsStockMov.Tables["StockMovDetalle"].Rows.Find(clave);
                    if (foundRow == null)
                    {
                        existe = false;
                    }
                    else
                    {
                        clave = rand.Next(1, 1000000000);
                    }
                }
                dgvDatos[0, e.RowIndex].Value = clave;
                dgvDatos[1, e.RowIndex].Value = Convert.ToInt32(lblNro.Text.ToString());
                dgvDatos["OrigenMSTKD", e.RowIndex].Value = 1;
                dgvDatos["DestinoMSTKD", e.RowIndex].Value = cmbDestino.SelectedValue;
            }
            if (String.IsNullOrEmpty(dgvDatos["CompensaMSTKD", e.RowIndex].Value.ToString()))
            {
                dgvDatos["CompensaMSTKD", e.RowIndex].Value = 1;
            }
        }

        private void dgvDatos_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is DataGridViewComboBoxEditingControl)
            {
                ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
                ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
                ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            }
            TextBox txt = e.Control as TextBox;
            if (dgvDatos.CurrentCell.ColumnIndex == 2 && txt != null)
            {
                var source = new AutoCompleteStringCollection();
                String[] stringArray =
                    Array.ConvertAll<DataRow, String>(tblArticulos.Select(), delegate(DataRow row) { return (String)row["IdArticuloART"]; });
                source.AddRange(stringArray);

                if (txt != null)
                {
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteCustomSource = source;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
            else if (dgvDatos.CurrentCell.ColumnIndex != 2 && txt != null)
            {
                if (txt != null)
                {
                    txt.AutoCompleteMode = AutoCompleteMode.None;
                    txt.AutoCompleteSource = AutoCompleteSource.None;
                }
            }
        }

        private void dgvDatos_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvDatos.CurrentRow.IsNewRow)
            {
                return;
            }
            dgvDatos.Rows[e.RowIndex].ErrorText = String.Empty;
            if (e.ColumnIndex == 2)
            {
                string articulo = dgvDatos.CurrentCell.EditedFormattedValue.ToString();
                DataRow[] foundRow = tblArticulos.Select("IdArticuloART = '" + articulo + "'");
                if (foundRow.Length != 0)
                {
                    DataRow filaActual = foundRow[0];
                    var fila = dgvDatos.CurrentCell.RowIndex;
                    this.dgvDatos[2, fila].Value = filaActual["IdArticuloART"].ToString();
                    this.dgvDatos[3, fila].Value = filaActual["DescripcionART"].ToString();
                }
                else if (foundRow.Length == 0)
                {
                    dgvDatos.Rows[e.RowIndex].ErrorText = "El código de artículo es inexistente.";
                    e.Cancel = true;
                }
            }
            if (e.ColumnIndex == 4)
            {
                var dato = dgvDatos.CurrentCell.EditedFormattedValue;
                bool result = Information.IsNumeric(dato);
                if (result == false)
                {
                    dgvDatos.Rows[e.RowIndex].ErrorText = "Debe ingresar un valor numérico";
                    e.Cancel = true;
                }
            }
        }

        private void ValidarFila(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvDatos.CurrentRow.IsNewRow)
            {
                return;
            }
            if (dgvDatos[2, e.RowIndex].Value == null || dgvDatos[2, e.RowIndex].Value.ToString() == "") // Articulo
            {
                dgvDatos.Rows[e.RowIndex].ErrorText = "Debe ingresar un código de artículo";
                dgvDatos.CurrentCell = dgvDatos[2, e.RowIndex];
                e.Cancel = true;
            }

            var dato = dgvDatos[4, e.RowIndex].Value;
            bool result = Information.IsNumeric(dato);
            if (result == false)
            {
                dgvDatos.Rows[e.RowIndex].ErrorText = "Debe ingresar un valor numérico en la columna CANTIDAD";
                dgvDatos.CurrentCell = dgvDatos[4, e.RowIndex];
                e.Cancel = true;
            }
        }

        private void dgvDatos_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            intFila = e.RowIndex;
        }

        private void validarMaestro()
        {
            try
            {
                if (cmbOrigen.SelectedIndex == -1 || cmbDestino.SelectedIndex == -1)
                {
                    dgvDatos.Enabled = false;
                }
                else
                {
                    dgvDatos.Enabled = true;
                }
            }
            catch (NullReferenceException)
            {
                dgvDatos.Enabled = false;
            }
        }

        private void dgvDatos_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDatos.RowCount > 1)
            {
                btnGrabar.Enabled = true;
            }
            btnArticulos.Enabled = true;
        }

        private void btnGrabar_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (tblStockMovDetalle.GetChanges() != null)
            {
                rowView.EndEdit();
                string formularioOrigen = "frmStockMov";
                string accionProgress = "grabar";
                progreso = new frmProgress(dsStockMov, formularioOrigen, accionProgress, rowView);
                progreso.Show();
            }
            else
            {
                tblStockMov.RejectChanges();
            }
            Cursor.Current = Cursors.Arrow;
            Close();
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnArticulos_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            frmArticulos articulos = new frmArticulos(ref instancia, intFila, tblArticulos);
            articulos.Show(this);
            // Vuelvo a activar el evento para futuras busquedas de artículos
            this.dgvDatos.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvDatos_RowEnter);
            Cursor.Current = Cursors.Arrow;
        }

        public DataGridView gridDatos
        {
            get
            {
                return this.dgvDatos;
            }
        }

    }
}
